package com.seekting.mynews.manager;

import android.content.Context;

import com.seekting.mynews.util.SharedPref;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by seekting on 2016/3/21.
 */
public class BitmapRatioManager extends Manager {

    private Map<String, Float> mRatioMap = new HashMap<String, Float>();

    public BitmapRatioManager(Context context) {
        super(context);
        syncRead();
    }

    public synchronized void putRatio(String key, float f) {
        mRatioMap.put(key, f);
        syncSave();
    }

    public synchronized float getRatio(String key) {
        return mRatioMap.get(key);
    }

    public synchronized void syncSave() {
        Iterator<Map.Entry<String, Float>> iterator = mRatioMap.entrySet().iterator();
        JSONArray jsonArray = new JSONArray();
        try {
            while (iterator.hasNext()) {
                Map.Entry<String, Float> entry = iterator.next();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name", entry.getKey());
                jsonObject.put("ratio", entry.getValue());
                jsonArray.put(jsonObject);

            }
            SharedPref.setString(mContext, SharedPref.SP_KEY_BITMAP_RATIO, jsonArray.toString());
        } catch (JSONException e) {
        }
    }

    public synchronized void syncRead() {
        String str = SharedPref.getString(mContext, SharedPref.SP_KEY_BITMAP_RATIO, null);
        if (str == null) {
            return;
        }
        try {
            JSONArray jsonArray = new JSONArray(str);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.optJSONObject(i);
                String name = jsonObject.optString("name");
                float ratio = (float) jsonObject.optDouble("ratio");
                mRatioMap.put(name, ratio);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}
